/**reg***/

#include "myhead.h"
#define OK 0 
#define SQLITE_OK 0
int reg(int id, int fd, struct message Msg)
{
//	printf("正在注册\n");
	
	sqlite3 *db;
	int rc;
	int in;
	rc = open_db(&db);
	if (rc == OK)
	{
		create_table(db);
		input(db,fd,Msg);	
		findreg(db,id,fd,Msg);
	}
	return 0;
}


/****************打开数据库********************/
open_db(sqlite3 **db)
{
	int rc;
	rc = sqlite3_open("reg.db",db);
	if (rc != SQLITE_OK)
	{
		printf("数据库打开失败\n");
		exit(1);
	}
	else
	{
		return OK;
	}
}


/***************新建数据库****************/
void create_table(sqlite3 *db)
{
	int rc;
	char *errmsg;
	rc=sqlite3_exec(db,"create table if not exists reg(id integer primary key autoincrement,name text,key text);",NULL,NULL,&errmsg);
	if (rc != SQLITE_OK)
	{
		printf("数据表创建失败:%s\n",errmsg);
		exit (-1);	
	}
}



/*************数据库输入*************/
void input(sqlite3 *db,int fd,struct message Msg)
{
	printf("正在注册\n");
	
	
	char sql[100];
	char *errmsg;
	int ret;
	char name[20],key[20];
	strcpy(name,"0");
	
	strcpy(key,"0");
	
	strcpy(name,Msg.name);
	strcpy(key,Msg.key);


	sprintf(sql,"insert into reg(name,key) values ('%s','%s');",name,key);
	ret = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
	if(ret != SQLITE_OK)
	{
		printf("name key 插入数据失败:%s\n", errmsg);
		exit (-1);	
	}
	printf("reg success");
	
}


/**********查找模式************/
void findreg(sqlite3 *db,int id, int fd, struct message Msg)
{
	

	int in, ret, i;
	char sql[100], who[20], name[20],key[20];
	char *errmsg;
	char sel;
	char **result;
	int row, column;

	strcpy(who, Msg.name);

	sprintf(sql, "select id from reg where name = '%s';",who);
	ret = sqlite3_get_table(db,sql,&result,&row,&column,&errmsg);	
	if(SQLITE_OK !=ret)
		{
			printf("error:%s\n",errmsg);
			exit(1);
		}
		
		if(row == 0)
		{
			printf("未找到该账号:\n");
		}
		else
		{
	
	
			printf("remember your id-----%s\n",result[row]);
	
//			Msg.id = *((int*)result[row]);
			strcpy(Msg.id,result[row]);
			printf("%s\n",Msg.id);


			strcpy(ssid,Msg.id);
			printf("ssid%s\n",ssid);
		}

}




